<script setup lang="ts">
import type { ReportColumnsItem } from '../types'
import { TIDS } from '../types'
import WrapComponent from './WrapComponent.vue'
import TableHead from './TableHead.vue'
import ContextmenuBox from './ContextmenuBox.vue'

import useArrowKey from './useArrowKey'
import useContextmenu from './useContextmenu'
import useReportCell from './useReportCell'
import useReportRow from './useReportRow'
import useLoadList from './useLoadList'
import useReportSave from './useReportSave'
import useReportInit from './useReportInit'

import { energyMetrologicalReviewApi } from '@/api'

const props = withDefaults(
  defineProps<{
    tId?: TIDS
    readonly?: boolean
  }>(),
  {
    tId: TIDS.LIST_OF_MEASURING_INSTRUMENTS,
  },
)
defineSlots<{
  title: (props: {
    title: string
    saveStage: () => any
  }) => any
  description: () => any
}>()

const title = computed(() => {
  const tId = props.tId
  let result = ''
  switch (tId) {
    case TIDS.LIST_OF_MEASURING_INSTRUMENTS:
      result = '能源计量器具一览表'
      break
    case TIDS.LIST_OF_ENERGY_MEASURING_INSTRUMENTS_FOR_UNIT_ENERGY_USE_IN_AND_OUT:
      result = '进出用能单位能源计量器具一览表分表'
      break
    case TIDS.ENTRY_AND_EXIT_OF_MAJOR_SECONDARY_UNIT_ENERGY_METERING_INSTRUMENTS:
      result = '进出主要次级用能单位能源计量器具一览表分表'
      break
    case TIDS.LIST_OF_ENERGY_MEASURING_INSTRUMENTS_FOR_MAJOR_ENERGY_USING_EQUIPMENT:
      result = '主要用能设备能源计量器具一览表分表'
      break
    case TIDS.LIST_OF_OTHER_ENERGY_MEASURING_INSTRUMENTS:
      result = '其他能源计量器具一览表分表'
      break
  }
  return result
})

/** 计量器具类型 */
const type = computed(() => {
  const tId = props.tId
  let result: 1 | 2 | 3 | 4 | undefined
  switch (tId) {
    case TIDS.LIST_OF_ENERGY_MEASURING_INSTRUMENTS_FOR_UNIT_ENERGY_USE_IN_AND_OUT:
      result = 1
      break
    case TIDS.ENTRY_AND_EXIT_OF_MAJOR_SECONDARY_UNIT_ENERGY_METERING_INSTRUMENTS:
      result = 2
      break
    case TIDS.LIST_OF_ENERGY_MEASURING_INSTRUMENTS_FOR_MAJOR_ENERGY_USING_EQUIPMENT:
      result = 3
      break
    case TIDS.LIST_OF_OTHER_ENERGY_MEASURING_INSTRUMENTS:
      result = 4
      break
  }
  return result
})
const columns: ReportColumnsItem[] = [
  { label: '计量器具名称', prop: 'name' },
  { label: '型号规格', prop: 'specification' },
  { label: '准确度等级', prop: 'accuracyLevel' },
  { label: '测量范围', prop: 'measuringRange' },
  { label: '生产厂家', prop: 'factory' },
  { label: '出厂编号', prop: 'factoryNumber' },
  { label: '用能单位管理编号', prop: 'useUnitNumber' },
  { label: '安装使用地点', prop: 'installationLocation' },
  { label: '检定周期/校准间隔', prop: 'verificationCycle' },
  { label: '状态（合格/准用/停用）', prop: 'status' },
]
const showLineNumber = ref(true)
const { lists, loading, loadList } = useLoadList(
  columns,
  () =>
    energyMetrologicalReviewApi.selectMeasuringTools(
      toValue(type),
    ),
  props.readonly,
  {
    fullTransfer: true,
  },
)

const { initInputIndex, inputIndex, clickCallback }
  = useReportCell()
const { left, top, rowIndex, onContextmenu }
  = useContextmenu()
const { delRow, appendRow, prependRow } = useReportRow(
  lists,
  columns,
  rowIndex,
)

const { saveStage } = useReportSave(
  lists,
  {},
  energyMetrologicalReviewApi.saveOrUpdateMeasuringTools,
  {
    preProcessData(data) {
      // 删除填报人信息
      data.pop()

      data.forEach((v) => {
        v.type = type.value
        v.status = +v.status
      })
    },
  },
)

useArrowKey(inputIndex, columns.length)
useReportInit(loadList, initInputIndex)
</script>

<template>
  <WrapComponent>
    <template v-if="$slots.title" #title>
      <slot
        name="title"
        :title="title"
        :save-stage="saveStage"
      />
    </template>
    <div
      v-loading="loading"
      class="width-fill height-fill flex-direction flex"
    >
      <div class="report-table-head">
        <table class="report-table">
          <TableHead
            :columns="columns"
            :show-line-number="showLineNumber"
          />
        </table>
      </div>
      <ElScrollbar>
        <table class="report-table" style="height: auto">
          <tbody ref="tbody">
            <tr v-for="(item, i) in lists" :key="item.uuid">
              <th
                v-if="showLineNumber"
                class="readonly width-40px line-number"
              >
                {{ i + 1 }}
              </th>
              <td
                v-for="(d, index) in item.data"
                :key="`${item.uuid}_${index}`"
              >
                <div v-if="!d.editable" class="span-cell">
                  {{ d.value }}
                </div>
                <div v-else class="input-cell">
                  <input
                    v-model="d.value"
                    type="text"
                    @click="clickCallback"
                    @contextmenu="
                      evt => onContextmenu(evt, i)
                    "
                  >
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <slot name="description">
          <div class="description-text">
            <p>注：状态（1-合格/2-准用/3-停用）</p>
          </div>
        </slot>
      </ElScrollbar>
      <ContextmenuBox
        :left="left"
        :top="top"
        @del-row="delRow"
        @prepend-row="prependRow"
        @append-row="appendRow"
      />
    </div>
  </WrapComponent>
</template>
